package com.ruoyi.system.controller;

import java.util.*;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysQuestion;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.diagnosis.ScoreUtil;
import com.ruoyi.system.domain.SysDiagnosisDetail;
import com.ruoyi.system.domain.SysNaire;
import com.ruoyi.system.service.ISysNaireService;
import com.ruoyi.system.service.ISysQuestionDomainService;
import com.ruoyi.system.service.ISysQuestionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.domain.entity.SysQuestionDomain;

import javax.swing.*;

/**
 * 问题领域Controller
 * 
 * @author ruoyi
 * @date 2022-05-07
 */
@Api(tags = "问题领域")
@RestController
@RequestMapping("/system/questiondomain")
public class SysQuestionDomainController extends BaseController
{


    @Autowired
    private ISysQuestionDomainService domainService;
    @Autowired
    private ISysNaireService sysNaireService;
    @Autowired
    private ISysQuestionService sysQuestionService;

    /**
     * 获取领域列表
     */
    //@PreAuthorize("@ss.hasPermi('system:domain:list')")
    @GetMapping("/list")
    public AjaxResult list(SysQuestionDomain domain)
    {
        List<SysQuestionDomain> domains = domainService.selectQuestionDomainList(domain);
        return AjaxResult.success(domains);
    }

    /**
     * 查询领域列表（排除节点）
     */
    //@PreAuthorize("@ss.hasPermi('system:domain:list')")
    @GetMapping("/list/exclude/{domainId}")
    public AjaxResult excludeChild(@PathVariable(value = "domainId", required = false) Long domainId)
    {
        List<SysQuestionDomain> domains = domainService.selectQuestionDomainList(new SysQuestionDomain());
        Iterator<SysQuestionDomain> it = domains.iterator();
        while (it.hasNext())
        {
            SysQuestionDomain d = (SysQuestionDomain) it.next();
            if (d.getDomainId().intValue() == domainId
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), domainId + ""))
            {
                it.remove();
            }
        }
        return AjaxResult.success(domains);
    }

    /**
     * 根据领域编号获取详细信息
     */
   // @PreAuthorize("@ss.hasPermi('system:domain:query')")
    @GetMapping(value = "/{domainId}")
    public AjaxResult getInfo(@PathVariable Long domainId)
    {
        domainService.checkQuestionDomainDataScope(domainId);
        return AjaxResult.success(domainService.selectQuestionDomainById(domainId));
    }



    /**
     * 获取领域下拉树列表
     */
  @GetMapping("/treeselect/{domainId}")
    public AjaxResult treeselect(@PathVariable Long domainId)
    {
        SysQuestionDomain domain=new SysQuestionDomain();
        domain.setDomainId(domainId);
        List<SysQuestionDomain> domains = domainService.selectQuestionDomainList(domain);
        return AjaxResult.success(domainService.buildQuestionDomainTreeSelect(domains));
    }

    /**
     * 获取领域下拉树列表
     */
   @GetMapping("/treeselect")
    public AjaxResult treeselect(SysQuestionDomain domain)
    {
        List<SysQuestionDomain> domains = domainService.selectQuestionDomainList(domain);
        return AjaxResult.success(domainService.buildQuestionDomainTreeSelect(domains));
    }

    @GetMapping("/treeselect2")
    public AjaxResult treeselect(@RequestParam("companyId") Long companyId, @RequestParam ("naireId")Long naireId)
    {


        SysQuestionDomain domain=new SysQuestionDomain();
        List<SysQuestionDomain> domains = domainService.selectQuestionDomainList(domain);

        SysNaire naire = sysNaireService.selectSysNaireByNaireId(naireId);
        List<String> quesetionIds = Arrays.asList(naire.getQuestions().substring(1, naire.getQuestions().length() - 1).split(","));


        HashMap<Long,SysQuestionDomain>domainMap=new HashMap<>();
        for (SysQuestionDomain tdomain:domains){
            domainMap.put(tdomain.getDomainId(),tdomain);
        }

        SysQuestion qquery=new SysQuestion();
        qquery.setNaireId(naireId);
        List<SysQuestion> questions = sysQuestionService.selectSysQuestionList(qquery);
        List<SysQuestionDomain> result = new ArrayList<>();
        List<Long> domainIds=new ArrayList<>();
        for (SysQuestion question : questions) {
            if (!quesetionIds.contains(question.getQuestionId() + "")) {
                continue;
            }
            if(!domainIds.contains(question.getDomain()))
                domainIds.add(question.getDomain());

        }

        for(SysQuestionDomain tdomain:domains){
            if(domainIds.contains(tdomain.getDomainId())){
                if(!result.contains(tdomain)){
                    result.add(tdomain);
                    String parent=tdomain.getAncestors();
                    List<String> parentIds=Arrays.asList(parent.split(","));
                    for (String parentId:parentIds) {
                        if (parentId.trim().length() == 0)
                            continue;
                        Long tid = Long.parseLong(parentId);
                        if (!domainMap.containsKey(tid))
                            continue;
                        if (!result.contains(domainMap.get(tid))) {
                            result.add(domainMap.get(tid));
                        }
                    }
                }

            }
        }

        return AjaxResult.success(domainService.buildQuestionDomainTreeSelect(result));
    }


    /**
     * 加载对应角色领域列表树
     */
    @GetMapping(value = "/roleQuestionDomainTreeselect/{roleId}")
    public AjaxResult roleQuestionDomainTreeselect(@PathVariable("roleId") Long roleId)
    {
        List<SysQuestionDomain> domains = domainService.selectQuestionDomainList(new SysQuestionDomain());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("domains", domainService.buildQuestionDomainTreeSelect(domains));
        return ajax;
    }

    /**
     * 新增领域
     */
   // @PreAuthorize("@ss.hasPermi('system:domain:add')")
    @Log(title = "领域管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysQuestionDomain domain)
    {
        if (UserConstants.NOT_UNIQUE.equals(domainService.checkQuestionDomainNameUnique(domain)))
        {
            return AjaxResult.error("新增领域'" + domain.getDomainName() + "'失败，领域名称已存在");
        }
        domain.setCreateBy(getUsername());
        return toAjax(domainService.insertQuestionDomain(domain));
    }

    /**
     * 新增领域
     */
   // @PreAuthorize("@ss.hasPermi('system:domain:add')")
    @Log(title = "领域管理", businessType = BusinessType.INSERT)
    @PostMapping("/addRootDomain")
    public AjaxResult addRootDomain(@Validated @RequestBody SysQuestionDomain domain)
    {
        domain.setCreateBy(getUsername());
        return toAjax(domainService.inserRootDomain(domain));
    }




    /**
     * 修改领域
     */
 //   @PreAuthorize("@ss.hasPermi('system:domain:edit')")
    @Log(title = "领域管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysQuestionDomain domain)
    {
        Long domainId = domain.getDomainId();
        domainService.checkQuestionDomainDataScope(domainId);
        if (UserConstants.NOT_UNIQUE.equals(domainService.checkQuestionDomainNameUnique(domain)))
        {
            return AjaxResult.error("修改领域'" + domain.getDomainName() + "'失败，领域名称已存在");
        }
        else if (domain.getParentId().equals(domainId))
        {
            return AjaxResult.error("修改领域'" + domain.getDomainName() + "'失败，上级领域不能是自己");
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, domain.getStatus()) && domainService.selectNormalChildrenQuestionDomainById(domainId) > 0)
        {
            return AjaxResult.error("该领域包含未停用的子领域！");
        }
        domain.setUpdateBy(getUsername());
        return toAjax(domainService.updateQuestionDomain(domain));
    }

    /**
     * 删除领域
     */
   // @PreAuthorize("@ss.hasPermi('system:domain:remove')")
    @Log(title = "领域管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{domainId}")
    public AjaxResult remove(@PathVariable Long domainId)
    {
        if (domainService.hasChildByQuestionDomainById(domainId))
        {
            return AjaxResult.error("存在下级领域,不允许删除");
        }
        if (domainService.checkQuestionDomainExistQuestion(domainId))
        {
            return AjaxResult.error("领域存在用户,不允许删除");
        }
        domainService.checkQuestionDomainDataScope(domainId);
        return toAjax(domainService.deleteQuestionDomainById(domainId));
    }


    @ApiOperation(value = "获取问卷领域树级结构")
    @GetMapping("/tree/select")
    public AjaxResult treeSelect(@RequestParam ("naireId")Long naireId)
    {


        SysQuestionDomain domain=new SysQuestionDomain();
        List<SysQuestionDomain> domains = domainService.selectQuestionDomainList(domain);

        SysNaire naire = sysNaireService.selectSysNaireByNaireId(naireId);
        List<String> quesetionIds = Arrays.asList(naire.getQuestions().substring(1, naire.getQuestions().length() - 1).split(","));


        HashMap<Long,SysQuestionDomain>domainMap=new HashMap<>();
        for (SysQuestionDomain tdomain:domains){
            domainMap.put(tdomain.getDomainId(),tdomain);
        }

        SysQuestion qquery=new SysQuestion();
        qquery.setNaireId(naireId);
        List<SysQuestion> questions = sysQuestionService.selectSysQuestionList(qquery);
        List<SysQuestionDomain> result = new ArrayList<>();
        List<Long> domainIds=new ArrayList<>();
        for (SysQuestion question : questions) {
            if (!quesetionIds.contains(question.getQuestionId() + "")) {
                continue;
            }
            if(!domainIds.contains(question.getDomain()))
                domainIds.add(question.getDomain());

        }

        for(SysQuestionDomain tdomain:domains){
            if(domainIds.contains(tdomain.getDomainId())){
                if(!result.contains(tdomain)){
                    result.add(tdomain);
                    String parent=tdomain.getAncestors();
                    List<String> parentIds=Arrays.asList(parent.split(","));
                    for (String parentId:parentIds) {
                        if (parentId.trim().length() == 0)
                            continue;
                        Long tid = Long.parseLong(parentId);
                        if (!domainMap.containsKey(tid))
                            continue;
                        if (!result.contains(domainMap.get(tid))) {
                            result.add(domainMap.get(tid));
                        }
                    }
                }

            }
        }

        return AjaxResult.success(domainService.buildQuestionDomainTreeSelect(result));
    }
}
